//
//  NSKExtension.swift
//  NSKExtension
//
//  Created by Fineland on 2021/3/8.
//
import UIKit

extension UIColor {

    class func fromHex(_ hexVal: Int, alpha: CGFloat = 1.0) -> UIColor {
        
        //16进制整型转换成颜色
        return UIColor(red: ((CGFloat)((hexVal & 0xFF0000) >> 16)) / 255.0,
                       green: ((CGFloat)((hexVal & 0xFF00) >> 8)) / 255.0, blue: ((CGFloat)(hexVal & 0xFF)) / 255.0,
                       alpha: alpha)
    }
}
// MARK: -

extension Array {
    
    func toModel<T>(_ type: T.Type) -> [T] where T: Codable {
        
        //将数据转成model对象
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: self, options: [])
            return try JSONDecoder().decode([T].self, from: jsonData)
        } catch {
            //异常处理
            #if DEBUG
            print("Array->Model失败")
            #endif
        }
        //返回：空对象
        return []
    }
}

// MARK: -

extension Dictionary {
    
    func toModel<T>(_ type: T.Type) -> T where T: Codable {
        
        //将数据转成model对象
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: self, options: [])
            return try JSONDecoder().decode(type, from: jsonData)
        } catch {
            //异常处理
            #if DEBUG
            print("Dictionary->Model失败")
            #endif
        }
        //返回：空对象
        return [] as! T
    }
}

// MARK: -

extension UIImage {

    class func fromColor(_ color: UIColor) -> UIImage {
        
        //图片大小
        let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
        //创建画布
        UIGraphicsBeginImageContext(rect.size)
        if let context = UIGraphicsGetCurrentContext() {
            //设定颜色
            context.setFillColor(color.cgColor)
            context.fill(rect)
        }
        //生成图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        //是否为空？
        guard let tempImage = image else {
            return UIImage()
        }
        //拉伸
        let newImage = tempImage.stretchableImage(withLeftCapWidth: 0, topCapHeight: Int(rect.size.height))
        //返回
        return newImage
    }
}

// MARK: -

extension String {
    
    func regularPhone() -> Bool {
        
        //手机号码第1位为1，其余的10都为数字即可
        let predicate = NSPredicate(format: "SELF MATCHES %@", "^[1]+\\d{10}$")
        //返回
        return predicate.evaluate(with: self)
    }
    
    func toDate(_ dateFormat: String = "yyyy-MM-dd HH:mm:ss") -> Date {
        
        //转换日期
        let formatter = DateFormatter()
        formatter.dateFormat = dateFormat
        //是否转换成功？
        guard let tempDate = formatter.date(from: self) else {
            return Date()
        }
        //返回
        return tempDate
    }
    
    func vc() -> UIViewController? {
        
        //类名
        let tempVal = "\(Bundle.main.infoDictionary!["CFBundleExecutable"]!).\(self)"
        guard let classObj = NSClassFromString(tempVal) else {
            return nil
        }
        //是否为"tableView"类型？
        if let tempObj = classObj as? UITableViewController.Type {
            return tempObj.init(style: .grouped)
        }
        //是否为空？
        guard let tempObj = classObj as? UIViewController.Type else {
            return nil
        }
        //返回
        return tempObj.init()
    }
    
    func color() -> UIColor {
        
        //颜色是否为空？
        return UIColor(named: self) ?? UIColor.black
    }
    
    func borderButton(_ target: Any, action: Selector, isBorder: Bool = true) -> UIButton {
        
        let nextButton = UIButton(type: .custom)
        nextButton.titleLabel?.font = UIFont.systemFont(ofSize: 16.0)
        nextButton.setTitleColor(NSKVar.C3_COLOR, for: .normal)
        nextButton.backgroundColor = UIColor.white
        //属性
        let tempAttr = [
            NSAttributedString.Key.foregroundColor: NSKVar.C9_COLOR,
            NSAttributedString.Key.font: UIFont.systemFont(ofSize: 26.0)
        ] as [NSAttributedString.Key : Any]
        //值
        let tempVal = NSMutableAttributedString(attributedString: NSAttributedString(string: "+ ", attributes: tempAttr))
        tempVal.append(NSAttributedString(string: self, attributes: [NSAttributedString.Key.baselineOffset: 2.0]))
        nextButton.setAttributedTitle(tempVal, for: .normal)
        //添加事件
        nextButton.addTarget(target, action: action, for: .touchUpInside)
        //nextButton.layer.cornerRadius = 3.0
        //是否需要边框？
        if false != isBorder {
            nextButton.layer.borderColor = NSKVar.SEPERATOR_COLOR.cgColor
            nextButton.layer.borderWidth = 0.5
        }
        //返回
        return nextButton
    }
    
    func button(with frame: CGRect, target: Any, action: Selector) -> UIButton {
        
        let nextButton = UIButton(type: .custom)
        nextButton.frame = frame
        nextButton.titleLabel?.font = UIFont.systemFont(ofSize: 17.0)
        nextButton.setTitleColor(UIColor.white, for: .normal)
        nextButton.setTitle(self, for: .normal)
        //渐变
        let bgLayer = CAGradientLayer()
        bgLayer.colors = [UIColor.fromHex(0x6FB7FF).cgColor, UIColor.fromHex(0x3698FB).cgColor]
        bgLayer.locations = [0.0, 1.0]
        bgLayer.frame = nextButton.bounds
        bgLayer.startPoint = CGPoint(x: 1.0, y: 0.8)
        bgLayer.endPoint = CGPoint(x: 0.0, y: 0.0)
        bgLayer.zPosition = -1
        //添加
        nextButton.layer.addSublayer(bgLayer)
        //添加事件
        nextButton.addTarget(target, action: action, for: .touchUpInside)
        //圆角
        nextButton.layer.cornerRadius = 0.5 * frame.size.height
        nextButton.clipsToBounds = true
        //返回
        return nextButton
    }
}

// MARK: -

extension Date {
    
    func toString(_ dateFormat: String = "yyyy-MM-dd HH:mm:ss") -> String {
        
        //转换日期
        let formatter = DateFormatter()
        formatter.dateFormat = dateFormat
        //返回
        return formatter.string(from: self)
    }
}

// MARK: -

extension Encodable {
    
    func dictionary() -> Dictionary<String, Any> {
        
        //将model转成对象
        do {
            let jsonData = try JSONEncoder().encode(self)
            let jsonObj = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments)
            if let tempData = jsonObj as? Dictionary<String, Any> {
                return tempData
            }
        } catch {
            //异常处理
            print("Encode出错->\(self)")
        }
        //返回
        return [:]
    }
    
    func array() -> Array<Dictionary<String, Any>> {
        
        //将model转成对象
        do {
            let jsonData = try JSONEncoder().encode(self)
            let jsonObj = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments)
            if let tempData = jsonObj as? Array<Dictionary<String, Any>> {
                return tempData
            }
        } catch {
            //异常处理
            print("Encode出错->\(self)")
        }
        //返回
        return []
    }
}

// MARK: -

extension UIViewController {
    
    func naviBarStyle(_ barColor: UIColor = UIColor.white, titleColor: UIColor = UIColor.black) -> Void {
        
        //当前navBar对象
        guard let navigationBar = self.navigationController?.navigationBar else {
            return
        }
        //navBar背景
        let tempImg = UIImage.fromColor(barColor)
        //let resizeImg = tempImg.resizableImage(withCapInsets: UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0),
        //                                       resizingMode: .stretch)
        navigationBar.setBackgroundImage(tempImg, for: .default)
        //是否去掉navBar的阴影，即有一条灰色分隔线
        navigationBar.shadowImage = UIImage()
        //设置状态栏的样式
        //navigationBar.barStyle = .blackOpaque
        //标题颜色、字体大小
        let tempAttr = [NSAttributedString.Key.foregroundColor: titleColor,
                        NSAttributedString.Key.font: UIFont.systemFont(ofSize: 19.0)]
        navigationBar.titleTextAttributes = tempAttr
        //隐藏系统自带返回按钮
        self.navigationItem.hidesBackButton = true
    }
    
    func naviBarTransparent() -> Void {
        
        //当前navBar对象
        guard let navigationBar = self.navigationController?.navigationBar else {
            return
        }
        //navBar背景
        let barColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)
        let tempImg = UIImage.fromColor(barColor)
        //let resizeImg = tempImg.resizableImage(withCapInsets: UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0),
        //                                       resizingMode: .stretch)
        navigationBar.setBackgroundImage(tempImg, for: .default)
        //去掉navBar的阴影，即有一条灰色分隔线
        navigationBar.shadowImage = UIImage()
        //隐藏系统自带返回按钮
        self.navigationItem.hidesBackButton = true
    }
    
    func leftItem(_ type: NSKLeftNaviBarItemType = .blackBack, width: CGFloat = 74.0) -> Void {
        
        //当前tag标识
        let tagVal: Int = 99
        let imgVal = UIImage(named: "\(type.rawValue)")
        //是否为空？
        if let tempView = self.navigationItem.leftBarButtonItem?.customView?.viewWithTag(tagVal) {
            (tempView as? UIImageView)?.image = imgVal
            return
        }
        //返回按钮
        let leftImgView = UIImageView(frame: CGRect(x: 0.0, y: 0.0, width: width, height: 44.0))
        leftImgView.image = imgVal
        leftImgView.tag = tagVal
        leftImgView.contentMode = .left
        leftImgView.isUserInteractionEnabled = true
        //添加返回手势
        leftImgView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(leftRecognizer(_:))))
        //设置
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftImgView)
        //隐藏系统自带的返回按钮
        self.navigationItem.hidesBackButton = true
    }
    
    @objc func canClose() -> Bool {
        
        return true
    }
    
    @objc func close() -> Void {
        
        //naviController对象
        if let naviController = self.navigationController {
            //先尝试pop对象
            if nil != naviController.popViewController(animated: true) {
                return
            }
            //'dismiss'方式关闭自己
            naviController.dismiss(animated: true) {
                
            }
            return
        }
        //'dismiss'方式关闭自己
        self.dismiss(animated: true) {
            
        }
    }
    
    @objc private func leftRecognizer(_ sender: UITapGestureRecognizer) -> Void {
        
        //是否可以返回？
        if true == canClose() {
            close()
        }
    }
}

// MARK: -

extension UIViewController {
    
    func pickerImageSourceType(_ sourceType: UIImagePickerController.SourceType, with delegate: Any) -> Void {
        
        //判断能否打开相册(或是相机)？
        guard true == UIImagePickerController.isSourceTypeAvailable(sourceType) else {
            return
        }
        //加载相册或是相册
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = delegate as? UIImagePickerControllerDelegate & UINavigationControllerDelegate
        imagePickerController.sourceType = sourceType
        imagePickerController.modalTransitionStyle = .coverVertical
        imagePickerController.allowsEditing = true
        //显示
        self.present(imagePickerController, animated: true, completion: { () -> Void in
            
        })
    }

//    func typeImageSource(with delegate: Any, maxCount: Int, assets: Array<Any>) -> Void {
//        
//        //图片选取
//        guard let naviController = TZImagePickerController(maxImagesCount: maxCount, columnNumber: 4,
//                                                           delegate: delegate as? TZImagePickerControllerDelegate,
//                                                           pushPhotoPickerVc: true) else {
//            return
//        }
//        //当前颜色
//        let tempColor = NSKVar.MAIN_COLOR
//        //naviBar样式
//        naviController.navigationBar.setBackgroundImage(UIImage.fromColor(tempColor), for: .default)
//        naviController.naviTitleFont = UIFont.systemFont(ofSize: 17.0)
//        naviController.barItemTextFont = UIFont.systemFont(ofSize: 16.0)
//        naviController.modalPresentationStyle = .fullScreen
//        //在内部显示拍照按钮、在内部显示拍视频按
//        naviController.allowTakePicture = true
//        naviController.allowTakeVideo = false
//        naviController.showPhotoCannotSelectLayer = true
//        naviController.cannotSelectLayerColor = UIColor.white.withAlphaComponent(0.7)
//        //只选择图片
//        naviController.allowPickingGif = false
//        naviController.allowPickingImage = true
//        naviController.allowPickingVideo = false
//        naviController.allowPickingOriginalPhoto = false
//        naviController.allowPreview = true
//        //设置是否显示图片序号
//        naviController.showSelectedIndex = false
//        //自定义“返回”
//        naviController.navLeftBarButtonSettingBlock = { (leftButton) -> Void in
//            leftButton?.setImage(UIImage(named: "navi_back_white"), for: .normal)
//            leftButton?.imageEdgeInsets = UIEdgeInsets(top: 0.0, left: -30.0, bottom: 0.0, right: 0.0)
//        }
//        //完成样式
//        naviController.oKButtonTitleColorDisabled = tempColor.withAlphaComponent(0.7)
//        naviController.oKButtonTitleColorNormal = tempColor
//        //图片列表是否大于0？
//        if assets.count > 0 {
//            naviController.selectedAssets = NSMutableArray(array: assets)
//        }
//        //显示
//        self.present(naviController, animated: true, completion: { () -> Void in
//            
//        })
//    }
}
